package com.auxgroup.smarthome.snoti;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;

// properties file searching order:
// 1. OS environment variables
// 2. -Dapplication.propertiesFile=<properties file full name>
// 3. <class path>/snoti.properties
public class Setting {
    private static final Logger logger = LoggerFactory.getLogger(Setting.class);
    private static volatile Properties properties = null;
    private static final String defaultFileName = "/snoti.properties";

    private static Properties getProperties() {
        if (properties == null) {
            synchronized (Setting.class) {
                if (properties == null) {
                    try {
                        Reader reader = new InputStreamReader(Setting.class.getResourceAsStream(defaultFileName), "UTF-8");
                        properties = new Properties();
                        properties.load(reader);
                    } catch (Exception e) {
                        logger.error("Load setting exception: {}", e.toString());
                    }
                }
            }
        }

        return properties;
    }

    public static String getValue(String key) {
        String result = null;

        result = System.getenv(key);

        if (result == null && getProperties() != null) {
            result = properties.getProperty(key);
        }

        return result;
    }
}
